package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class UserInfoApiImpl implements UserInfoApi {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setCreated(new Date());
        userInfo.setUpdated(new Date());
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfo.setUpdated(new Date());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long userId) {
        return userInfoMapper.selectById(userId);
    }

    @Override
    public IPage<UserInfo> findUserList(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<>(page, pagesize), null);
    }

    /**
     * 冻结用户
     *
     * @param userId
     */
    @Override
    public void freezeUser(Long userId) {
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, userId));
        userInfo.setUserStatus("2");
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 解冻用户
     *
     * @param userId
     */
    @Override
    public void unfreezeUser(Long userId) {
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, userId));
        userInfo.setUserStatus("1");
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 更新所有的用户的封禁状态
     */
    @Override
    public void updateUserStatus(List<Long> ids) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        if (ids == null || ids.size() == 0) {
            wrapper.eq(UserInfo::getUserStatus, "2");
        } else {
            wrapper.eq(UserInfo::getUserStatus, "2").notIn(UserInfo::getId, ids);
        }
        List<UserInfo> userInfoList = userInfoMapper.selectList(wrapper);
        if (userInfoList != null && userInfoList.size() > 0) {
            for (UserInfo userInfo : userInfoList) {
                unfreezeUser(userInfo.getId());
            }
        }
    }

    @Override
    public List<UserInfo> query() {
        return userInfoMapper.selectList(null);
    }
}
